package com.red.wine.util;

import java.io.ByteArrayOutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.Base64;

public class BitmapUtil {
	public static Bitmap rotateBitmap(Context context, float rotate,
			Bitmap bitmap) {
		Bitmap img = bitmap;
		Matrix matrix = new Matrix();
		matrix.postRotate(rotate); /* 翻转rotate度 */
		int width = img.getWidth();
		int height = img.getHeight();
		Bitmap r_img = Bitmap.createBitmap(img, 0, 0, width, height, matrix,
				true);
		return r_img;
	}

	public static Bitmap drawable2Bitmap(Drawable drawable) {
		BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable;
		return bitmapDrawable.getBitmap();
	}

	public static Bitmap getPicFromBytes(byte[] bytes,
			BitmapFactory.Options opts) {
		if (bytes != null)
			if (opts != null)
				return BitmapFactory.decodeByteArray(bytes, 0, bytes.length,
						opts);
			else
				return BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
		return null;
	}
	
	/**
	 *  将图片转换为二进制数组的方法   
	 * @param bitmap
	 * @return
	 */
    public static byte[] bitmapToBytes(Bitmap bitmap) {   
        if (bitmap == null) {   
            return null;   
        }   
        final ByteArrayOutputStream os = new ByteArrayOutputStream();   
        // 将Bitmap压缩成PNG编码，质量为100%存储   
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, os);// 除了PNG还有很多常见格式，如jpeg等。   
        return os.toByteArray();   
    }  
    
	/**
	 * 将数组转换成字符串
	 * 
	 * @param tBytes
	 * @return
	 */
	public String byteToBase64(byte[] tBytes) {
		String tString = "";
		String tSentString = "";

		tString = Base64.encodeToString(tBytes, 0);
		try {
			tSentString = URLEncoder.encode(tString, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return tSentString;
	}
}
